package cn.mf.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static cn.mf.hrm.constant.MsgQueueConstant.*;

/**
 * 消息队列配置
 */
@Configuration
public class MQConfig {
    //创建交换机
    @Bean
    public Exchange exchangeNameTopic(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME_TOPIC).build();
    }

    /*创建消息对象*/
    //定义短信的队列Bean
    @Bean
    public Queue msgQueue(){
        return new Queue(QUEUE_MSG);
    }
    //定义邮件的队列Bean
    @Bean
    public Queue emailQueue(){
        return new Queue(QUEUE_EMAIL);
    }
    //定义站内信的队列Bean
    @Bean
    public Queue smsgQueue(){
        return new Queue(QUEUE_SMSG);
    }

    /*绑定消息*/
    //绑定短信队列
    @Bean
    public Binding bindMsgQueue(){
        return BindingBuilder
                .bind(msgQueue())  //绑定队列
                .to(exchangeNameTopic()) //到哪个交换机
                .with("#.msg")  //用什么routingkey
                .noargs();
    }
    //绑定短信队列
    @Bean
    public Binding bindEmailQueue(){
        return BindingBuilder
                .bind(emailQueue())  //绑定队列
                .to(exchangeNameTopic()) //到哪个交换机
                .with("#.email")  //用什么routingkey
                .noargs();
    }
    //绑定短信队列
    @Bean
    public Binding bindSmsgQueue(){
        return BindingBuilder
                .bind(smsgQueue())  //绑定队列
                .to(exchangeNameTopic()) //到哪个交换机
                .with("#.smsg")  //用什么routingkey
                .noargs();
    }

    //自定义RabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //如果消息发送到MQ失败，把消息返回回来
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

}
